import React, { useState } from 'react'
import { Card, Table, Button, Modal, Tag, Space, message, Row, Col, Alert, Timeline } from 'antd'
import { SafetyOutlined, EyeOutlined, CheckOutlined, CloseOutlined, WarningOutlined } from '@ant-design/icons'
import Layout from '../components/Layout/Layout'

export default function Security() {
  const [alerts, setAlerts] = useState([
    { id: 1, type: 'intrusion', location: 'B区入口', description: '检测到异常行为', time: '2024-01-15 14:25:12', status: 'pending', level: 'high' },
    { id: 2, type: 'fire', location: 'E区仓库', description: '烟雾报警器触发', time: '2024-01-15 13:45:33', status: 'resolved', level: 'critical' },
    { id: 3, type: 'access', location: 'A区大门', description: '未授权刷卡尝试', time: '2024-01-15 12:30:15', status: 'investigating', level: 'medium' },
    { id: 4, type: 'equipment', location: 'C区3楼', description: '监控设备离线', time: '2024-01-15 11:15:22', status: 'pending', level: 'low' },
  ])

  const [cameras, setCameras] = useState([
    { id: 1, name: '主入口摄像头', location: 'A区大门', status: 'online', recording: true },
    { id: 2, name: '停车场摄像头', location: 'B区停车场', status: 'online', recording: true },
    { id: 3, name: '办公区摄像头', location: 'C区3楼', status: 'offline', recording: false },
    { id: 4, name: '仓库摄像头', location: 'E区仓库', status: 'online', recording: true },
  ])

  const [accessLogs, setAccessLogs] = useState([
    { id: 1, person: '张三', cardId: '001234', location: 'A区大门', action: 'entry', time: '2024-01-15 09:00:15', result: 'success' },
    { id: 2, person: '李四', cardId: '001235', location: 'B区入口', action: 'entry', time: '2024-01-15 08:30:22', result: 'success' },
    { id: 3, person: '未知', cardId: '999999', location: 'A区大门', action: 'entry', time: '2024-01-15 12:30:15', result: 'denied' },
    { id: 4, person: '王五', cardId: '001236', location: 'A区大门', action: 'exit', time: '2024-01-15 18:00:08', result: 'success' },
  ])

  const alertLevelColors = {
    critical: 'red',
    high: 'orange',
    medium: 'yellow',
    low: 'blue'
  }

  const alertLevelTexts = {
    critical: '紧急',
    high: '高',
    medium: '中',
    low: '低'
  }

  const alertTypeTexts = {
    intrusion: '入侵检测',
    fire: '火灾报警',
    access: '门禁异常',
    equipment: '设备故障'
  }

  const statusColors = {
    pending: 'orange',
    investigating: 'blue',
    resolved: 'green'
  }

  const statusTexts = {
    pending: '待处理',
    investigating: '处理中',
    resolved: '已解决'
  }

  const alertColumns = [
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (type: string) => alertTypeTexts[type] || type,
    },
    {
      title: '位置',
      dataIndex: 'location',
      key: 'location',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '时间',
      dataIndex: 'time',
      key: 'time',
    },
    {
      title: '级别',
      dataIndex: 'level',
      key: 'level',
      render: (level: string) => (
        <Tag color={alertLevelColors[level]}>{alertLevelTexts[level]}</Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag color={statusColors[status]}>{statusTexts[status]}</Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          {record.status === 'pending' && (
            <>
              <Button 
                type="link" 
                icon={<CheckOutlined />}
                onClick={() => handleResolveAlert(record)}
              >
                处理
              </Button>
              <Button 
                type="link" 
                onClick={() => handleInvestigateAlert(record)}
              >
                调查
              </Button>
            </>
          )}
          {record.status === 'investigating' && (
            <Button 
              type="link" 
              icon={<CheckOutlined />}
              onClick={() => handleResolveAlert(record)}
            >
              解决
            </Button>
          )}
          <Button 
            type="link" 
            icon={<EyeOutlined />}
            onClick={() => handleViewDetails(record)}
          >
            详情
          </Button>
        </Space>
      ),
    },
  ]

  const cameraColumns = [
    {
      title: '摄像头名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '位置',
      dataIndex: 'location',
      key: 'location',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag color={status === 'online' ? 'green' : 'red'}>
          {status === 'online' ? '在线' : '离线'}
        </Tag>
      ),
    },
    {
      title: '录制状态',
      dataIndex: 'recording',
      key: 'recording',
      render: (recording: boolean) => (
        <Tag color={recording ? 'green' : 'red'}>
          {recording ? '录制中' : '未录制'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button type="link" onClick={() => handleViewCamera(record)}>
            查看
          </Button>
          <Button 
            type="link" 
            onClick={() => handleToggleRecording(record)}
          >
            {record.recording ? '停止录制' : '开始录制'}
          </Button>
        </Space>
      ),
    },
  ]

  const accessColumns = [
    {
      title: '人员',
      dataIndex: 'person',
      key: 'person',
    },
    {
      title: '卡号',
      dataIndex: 'cardId',
      key: 'cardId',
    },
    {
      title: '位置',
      dataIndex: 'location',
      key: 'location',
    },
    {
      title: '动作',
      dataIndex: 'action',
      key: 'action',
      render: (action: string) => action === 'entry' ? '进入' : '离开',
    },
    {
      title: '时间',
      dataIndex: 'time',
      key: 'time',
    },
    {
      title: '结果',
      dataIndex: 'result',
      key: 'result',
      render: (result: string) => (
        <Tag color={result === 'success' ? 'green' : 'red'}>
          {result === 'success' ? '成功' : '拒绝'}
        </Tag>
      ),
    },
  ]

  const handleResolveAlert = (record) => {
    setAlerts(prev => 
      prev.map(alert => 
        alert.id === record.id ? { ...alert, status: 'resolved' } : alert
      )
    )
    message.success('警报已解决')
  }

  const handleInvestigateAlert = (record) => {
    setAlerts(prev => 
      prev.map(alert => 
        alert.id === record.id ? { ...alert, status: 'investigating' } : alert
      )
    )
    message.success('开始调查')
  }

  const handleViewDetails = (record) => {
    Modal.info({
      title: '警报详情',
      content: (
        <div>
          <p><strong>类型:</strong> {alertTypeTexts[record.type]}</p>
          <p><strong>位置:</strong> {record.location}</p>
          <p><strong>描述:</strong> {record.description}</p>
          <p><strong>时间:</strong> {record.time}</p>
          <p><strong>级别:</strong> {alertLevelTexts[record.level]}</p>
          <p><strong>状态:</strong> {statusTexts[record.status]}</p>
        </div>
      ),
    })
  }

  const handleViewCamera = (record) => {
    Modal.info({
      title: `查看摄像头 - ${record.name}`,
      content: (
        <div style={{ textAlign: 'center' }}>
          <div style={{ 
            width: '100%', 
            height: 300, 
            backgroundColor: '#f0f0f0', 
            display: 'flex', 
            alignItems: 'center', 
            justifyContent: 'center',
            marginBottom: 16
          }}>
            {record.status === 'online' ? '实时视频画面' : '摄像头离线'}
          </div>
          <p>位置: {record.location}</p>
          <p>状态: {record.status === 'online' ? '在线' : '离线'}</p>
        </div>
      ),
      width: 600,
    })
  }

  const handleToggleRecording = (record) => {
    setCameras(prev => 
      prev.map(camera => 
        camera.id === record.id 
          ? { ...camera, recording: !camera.recording }
          : camera
      )
    )
    message.success(record.recording ? '录制已停止' : '录制已开始')
  }

  const pendingAlerts = alerts.filter(alert => alert.status === 'pending')
  const criticalAlerts = alerts.filter(alert => alert.level === 'critical')

  return (
    <Layout>
      <div style={{ padding: '24px' }}>
        {/* 紧急警报提示 */}
        {criticalAlerts.length > 0 && (
          <Alert
            message={`紧急警报: 发现 ${criticalAlerts.length} 个紧急安全事件需要立即处理`}
            type="error"
            showIcon
            closable
            style={{ marginBottom: 16 }}
          />
        )}

        {/* 待处理警报提示 */}
        {pendingAlerts.length > 0 && (
          <Alert
            message={`您有 ${pendingAlerts.length} 个安全警报待处理`}
            type="warning"
            showIcon
            closable
            style={{ marginBottom: 16 }}
          />
        )}

        <Row gutter={16} style={{ marginBottom: 24 }}>
          <Col span={12}>
            <Card title="安全警报" extra={<WarningOutlined style={{ color: '#ff4d4f' }} />}>
              <Table
                columns={alertColumns}
                dataSource={alerts}
                rowKey="id"
                pagination={{ pageSize: 5 }}
                size="small"
              />
            </Card>
          </Col>
          <Col span={12}>
            <Card title="监控摄像头">
              <Table
                columns={cameraColumns}
                dataSource={cameras}
                rowKey="id"
                pagination={false}
                size="small"
              />
            </Card>
          </Col>
        </Row>

        <Card title="门禁记录">
          <Table
            columns={accessColumns}
            dataSource={accessLogs}
            rowKey="id"
            pagination={{ pageSize: 10 }}
          />
        </Card>
      </div>
    </Layout>
  )
}
